package com.liuzhu.chaoshikucungunli.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesManager {
    private static final String PREF_NAME = "LoginPrefs";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_REMEMBER_PASSWORD = "rememberPassword";
    private static final String KEY_SAVED_PASSWORD = "savedPassword";

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private static SharedPreferencesManager instance;

    private SharedPreferencesManager(Context context) {
        pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = pref.edit();
    }

    public static synchronized SharedPreferencesManager getInstance(Context context) {
        if (instance == null) {
            instance = new SharedPreferencesManager(context);
        }
        return instance;
    }

    public void setLoginStatus(boolean isLoggedIn, long userId, String username) {
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
        editor.putLong(KEY_USER_ID, userId);
        editor.putString(KEY_USERNAME, username);
        editor.apply();
    }

    public boolean isLoggedIn() {
        return pref.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public long getUserId() {
        return pref.getLong(KEY_USER_ID, -1);
    }

    public String getUsername() {
        return pref.getString(KEY_USERNAME, "");
    }

    public void saveLoginCredentials(String username, String password) {
        editor.putBoolean(KEY_REMEMBER_PASSWORD, true);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_SAVED_PASSWORD, password);
        editor.apply();
    }

    public void clearLoginCredentials() {
        editor.putBoolean(KEY_REMEMBER_PASSWORD, false);
        editor.remove(KEY_SAVED_PASSWORD);
        editor.apply();
    }

    public boolean isRememberPassword() {
        return pref.getBoolean(KEY_REMEMBER_PASSWORD, false);
    }

    public String getSavedUsername() {
        return pref.getString(KEY_USERNAME, "");
    }

    public String getSavedPassword() {
        return pref.getString(KEY_SAVED_PASSWORD, "");
    }

    public void logout() {
        editor.putBoolean(KEY_IS_LOGGED_IN, false);
        editor.remove(KEY_USER_ID);
        editor.remove(KEY_USERNAME);
        if (!isRememberPassword()) {
            clearLoginCredentials();
        }
        editor.apply();
    }
} 